<script setup lang="ts">
import {onMounted, onUnmounted, ref} from "vue";
import * as Phaser from "phaser";
import {Ocean1Main} from "./scenes/Ocean1Main.ts";
import {Source, StartParams} from "@/sys/models.ts";
import {Ocean1Preloader} from "@/scenes/Ocean1Preloader.ts";

let game: Phaser.Game;
let ocean1Game: Ocean1Main;

const query = new URLSearchParams(window.location.search);
// 游戏难度
const numbers = query.get('grade')?.split(',').map(i => parseInt(i)) ?? [];
const disturbs = query.get('dis')?.split(',').map(i => parseInt(i)) ?? [];
// 类型，1-教学 2-评估 3-训练
const mode = query.get('mode') ?? '1';
// 场景，1-执行抑制 2-多维度 3-综合认知能力
const scene = query.get('scene') ?? '1';
const att = query.get('att') ?? '-1';
// 平台，tt抖音，默认wx
const platform = query.get('platform') ?? 'wx';
const uid = query.get('uid') ?? '1064';
const token = query.get('token') ?? '';
// 环境，1线上、0开发
const product = query.get('pro') ?? '1';
const gameSceneRule = [
  [],
  ['1、手指拖动小财神撞击以下<span style="color:red">目标</span>：', '2、拖动小财神撞击（收集）一排中的<span style="color:red">目标数字</span>'],
  ['1、拖动小财神撞击（收集）以下<span style="color:red">目标</span>：', '2、拖动小财神撞击（收集）一排中的<span style="color:red">目标数字</span>；', '3、底部出现<span style="color:red">红圈目标</span>，用手指点击消除'],
  ['1、拖动小财神按目标顺序撞击（收集）以下<span style="color:red">目标</span>：', '注：请记住目标顺序', '2、拖动小财神撞击（收集）一排中的<span style="color:red">目标数字</span>；', '3、底部出现<span style="color:red">红圈目标</span>，用手指点击消除']
]
const pageTitles = ['', '执行抑制', '多维度', '综合认知']
const state = ref({
  showStart: false,
  showScore: false,
  scoreData: {
    score: 0,
    right: 0,
    error: 0,
    rightTime: '0',
    rightRate: '0',
    eRight: 0,
    eError: 0,
    eRate: '0',
    attention: 0
  },
  rules: [''],
  attention: -1,
  pageHidden: false,
});

onMounted(() => {
  state.value.showStart = true;
  const sceneValue = parseInt(scene)
  state.value.rules = gameSceneRule[sceneValue];
  document.title = pageTitles[sceneValue];
  state.value.attention = parseInt(att);

  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') {
      state.value.pageHidden = true;
      ocean1Game && ocean1Game.resumeMusic(true);
    } else {
      if (state.value.pageHidden) {
        state.value.pageHidden = false;
        ocean1Game && ocean1Game.resumeMusic(false);
      }
    }
  }, false)
})

onUnmounted(() => {
  game?.destroy(true)
})

const getAssetURL = (item: number) => {
  return new URL(`/src/assets/rules/rule_${item}.webp`, import.meta.url).href
}

const onStartGame = () => {
  state.value.showStart = false;
  const att = state.value.attention;
  const dpr = window.devicePixelRatio || 1;
  const startParams: StartParams = {
    scene: parseInt(scene),
    mode: parseInt(mode),
    numbers: numbers,
    disturbs: disturbs,
    attention: att,
    uid: uid,
    token: token,
    product: product == '1',
    callback: onGameOver
  }
  ocean1Game = new Ocean1Main(startParams);
  game = new Phaser.Game({
    parent: "gameContainer",
    type: Phaser.AUTO,
    width: window.innerWidth * dpr,
    height: window.innerHeight * dpr,
    scale: {
      mode: Phaser.Scale.FIT,
    },
    audio: {
      disableWebAudio: false,
    },
    physics: {
      default: "arcade",
      arcade: {
        debug: false,
      },
    },
    scene: [new Ocean1Preloader(mode), ocean1Game],
  });
}
// 游戏结束
const onGameOver = (data: Source) => {
  const right = data.reactionCount.filter((i: number) => i == 1).length;
  const error = data.reactionCount.length - right;
  const sum = data.rightTime.reduce((acc: number, curr: number) => acc + curr, 0);
  const rightRate = ((right / data.reactionCount.length) * 100).toFixed(0);
  const eRight = data.restrainCount.filter((i: number) => i == 1).length;
  const eError = data.restrainCount.length - eRight;
  const eRate = ((eRight / data.restrainCount.length) * 100).toFixed(0);
  const rTime = Math.floor(sum / data.rightTime.length)
  state.value.scoreData = {
    score: data.source,
    right: right,
    error: error,
    rightTime: isNaN(rTime) ? '0' : rTime.toString(),
    rightRate: rightRate,
    eRight: eRight,
    eError: eError,
    eRate: eRate,
    attention: data.attention
  };
  // 只有教学才有这个成绩弹窗
  if (mode === '1') {
    state.value.showScore = true;
    return;
  }
  onStopGame()
}

const onStopGame = () => {
  if (platform == 'tt') {
    window.tt.miniProgram.postMessage({data: state.value.scoreData});
    window.tt.miniProgram.navigateBack();
    return
  }
  window.wx.miniProgram.postMessage({data: state.value.scoreData});
  window.wx.miniProgram.navigateBack();
}

</script>

<template>
  <div id="gameContainer"/>
  <div v-if="state.showStart" class="dialog">
    <div class="container">
      <div class="title" style="font-weight: 600">必看必记</div>
      <img class="star" src="@assets/img_star_star.webp" alt=""/>
      <div class="slot">
        <view class="col" v-for="(item, index) in state.rules" :key="index">
          <view class="item" v-html="item"></view>
          <view v-if="index == 0" class="row img-container">
            <img class="rule-img" v-for="(item,index) in numbers" :src="getAssetURL(item)"
                 alt="" :key="index"/>
          </view>
        </view>
      </div>
      <view class="col" v-if="mode == '3' && platform == 'wx'">
        <span class="tips">
          训练中，出现困倦和疲惫，这正是大脑调用认知能力的表现，说明你的大脑认知耐力不足，平时不思考或者短视频游戏等玩多了原因造成的。因此更加需要每天进行大脑认知训练，否则大脑衰退风险系数会增高。还有个神奇功效是，大部分人睡前训练有助于入睡，提升睡眠质量。
        </span>
      </view>
      <button style="width: 70%;" @click="onStartGame">记住红包样式和规则，请开始</button>
    </div>
  </div>
  <div v-if="state.showScore" class="score-dialog">
    <div class="container">
      <img class="title-bg" src="@assets/img_dialog_title.webp" alt=""/>
      <div class="title">{{ state.scoreData.score }}分</div>
      <div class="slot">
        <div class="row">
          <div class="col item">
            <div class="value">{{ state.scoreData.right }}</div>
            <div class="key">反应正确</div>
          </div>
          <div class="col item">
            <div class="value">{{ state.scoreData.error }}</div>
            <div class="key">反应错误</div>
          </div>
          <div class="col item">
            <div class="value">{{ scene == '1' ? '--' : state.scoreData.rightTime + 'ms' }}</div>
            <div class="key">正确反应时</div>
          </div>
          <div class="col item">
            <div class="value">{{ state.scoreData.rightRate }}%</div>
            <div class="key">反应正确率</div>
          </div>
        </div>
        <div class="row" style="margin-top: 16px;">
          <div class="col item">
            <div class="value">{{ state.scoreData.eRight }}</div>
            <div class="key">抑制正确</div>
          </div>
          <div class="col item">
            <div class="value">{{ state.scoreData.eError }}</div>
            <div class="key">抑制错误</div>
          </div>
          <div class="col item">
            <div class="value">{{ state.scoreData.eRate }}%</div>
            <div class="key">抑制正确率</div>
          </div>
          <!--          <div class="col">-->
          <!--            <div class="value">87</div>-->
          <!--            <div class="key">注意力</div>-->
          <!--          </div>-->
        </div>
      </div>
      <div style="font-size: 12px; color:#999999; margin-bottom: 16px;">若成绩＞27分，请前往月度评估，否则继续新手教学
      </div>
      <button @click="onStopGame">我知道了</button>
    </div>
  </div>
</template>

<style scoped>
#gameContainer {
  width: 100%;
  height: 100vh;
  background-image: url("/src/assets/images/ready_bg.webp");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.row {
  display: flex;
  justify-content: center;
  flex-direction: row;
}

.col {
  display: flex;
  justify-content: center;
  flex-direction: column;
}

button {
  background-color: #55CC66;
  border: none;
  width: 133px;
  height: 36px;
  margin-bottom: 16px;
  border-radius: 18px;
  color: white;
}

.dialog {
  position: absolute;
  top: 150px;
  left: 0;
  right: 0;
  z-index: 1;
  display: flex;
  flex-direction: row;

  .container {
    margin: 0 auto;
    width: calc(100vw - 80px);
    background-color: white;
    border-radius: 5px;
    text-align: center;

    .title {
      height: 60px;
      line-height: 60px;
      font-size: 18px;
      color: #55CC66;
      background-color: #BBE4C1;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }

    .star {
      position: absolute;
      height: 47px;
      width: 240px;
      left: 60px;
      top: 4px
    }

    .slot {
      font-size: 13px;
      margin: 16px 0;
      color: #999999;

      .img-container {
        margin: 0 auto;
        width: 200px;
        padding: 16px 0;
        flex-wrap: wrap;
      }

      .rule-img {
        display: inline-block;
        width: 50px;
        height: 50px;
      }
    }

    .tips {
      font-size: 12px;
      color: #999999;
      margin: 16px;
      text-align: start;
    }
  }
}

.score-dialog {
  position: absolute;
  top: calc(100vh - 70%);
  left: 0;
  right: 0;
  z-index: 1;
  display: flex;
  flex-direction: row;

  .container {
    margin: 0 auto;
    width: calc(100vw - 80px);
    background-color: white;
    border-radius: 5px;
    text-align: center;

    .title-bg {
      width: 170px;
      position: relative;
      top: -20px;
    }

    .title {
      margin-top: -70px;
      height: 50px;
      line-height: 60px;
      font-size: 30px;
      color: #E98A0F;
      padding-top: 10px;
      background-color: #BBE4C1;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }

    .slot {
      margin: 16px 0;

      .item {
        margin: 0 8px;
      }

      .key {
        font-size: 11px;
        color: #666666;
      }

      .value {
        font-weight: 500;
        font-size: 18px;
        color: #55CC66;
      }
    }
  }
}
</style>
